import { ActionConstant } from '../actions/search_action';
import { initState, reduceEditState } from './search_reducer';
import { Map } from 'immutable'

export default function search_command(state, action) {
    switch (action.type) {
        case ActionConstant.type_editor_command_site:
            let new_content = state.get('content').set('site', action.value);
            return state.set('content', new_content);
        case ActionConstant.type_editor_command_intitle:
            return editInput(state, action, 'intitle');
        case ActionConstant.type_editor_command_inurl:
            return editInput(state, action, 'inurl');
        case ActionConstant.type_editor_command_inanchor:
            return editInput(state, action, 'inanchor');
        case ActionConstant.type_clear_command:
            return Map(initState.search_command);
        default:
            if(!state)
                return Map(initState.search_command);
            return state;
    }
}

function editInput(state, action, key) {
    let data = state.get('content').get(key);
    data = reduceEditState(data, action.former_text, action.current_text, action.index);
    let new_content = state.get('content').set(key, data);
    return state.set('content', new_content);
}

